package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.constant.IdempotentConstants;
import cn.itsource.ymcc.constant.KillConstants;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.query.CourseOrderQuery;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.result.PageList;
import cn.itsource.ymcc.util.UserContext;
import cn.itsource.ymcc.vo.CourseOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/courseOrder")
public class CourseOrderController {

    @Autowired
    public ICourseOrderService courseOrderService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/killPlaceOrder")
    public JsonResult killPlaceOrder(@RequestBody CourseOrderVo courseOrderVo, HttpServletRequest request){
        Boolean hasKey = redisTemplate.hasKey(KillConstants.KEY_PREFIX_PRE_ORDER + courseOrderVo.getOrderNo());
        if(!hasKey){
            return JsonResult.error("秒杀资格已失效");
        }
        if (idempotent(courseOrderVo)){
            return JsonResult.error("请勿重复提交");
        }
        String token = request.getHeader(UserContext.JWT_TOKEN_NAME);
        Long userId = UserContext.getUserId(token);
        return courseOrderService.killPlaceOrder(courseOrderVo,userId);
    }

    private boolean idempotent(@RequestBody CourseOrderVo courseOrderVo) {
        //什么幂等性
        List<Long> courseIds = courseOrderVo.getCourseIds();
        String ids = courseIds.stream().map(id -> id.toString()).collect(Collectors.joining(","));
        Object code = redisTemplate.opsForValue().get(IdempotentConstants.IDEMPOTENT + ids);
        if (code == null) {
            return true;
        }
        redisTemplate.delete(IdempotentConstants.IDEMPOTENT + ids);
        return false;
    }


    @PostMapping("/placeOrder")
    public JsonResult placeOrder(@RequestBody CourseOrderVo courseOrderVo, HttpServletRequest request){
        //什么幂等性
        if (idempotent(courseOrderVo)) return JsonResult.error("请勿重复提交");
        String token = request.getHeader(UserContext.JWT_TOKEN_NAME);
        Long userId = UserContext.getUserId(token);
        return courseOrderService.placeOrder(courseOrderVo,userId);
    }

    /**
    * 保存和修改公用的
    */
    @PostMapping("/save")
    public JsonResult saveOrUpdate(@RequestBody CourseOrder courseOrder){
        if(courseOrder.getId()!=null){
            courseOrderService.updateById(courseOrder);
        }else{
            courseOrderService.save(courseOrder);
        }
        return JsonResult.success();
    }

    /**
    * 删除对象
    */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long id){
        courseOrderService.removeById(id);
        return JsonResult.success();
    }

    /**
   * 获取对象
   */
    @GetMapping("/{id}")
    public JsonResult get(@PathVariable("id")Long id){
        return JsonResult.success().setData(courseOrderService.getById(id));
    }


    /**
    * 查询所有对象
    */
    @GetMapping("/list")
    public JsonResult list(){
        return JsonResult.success().setData(courseOrderService.list(null));
    }


    /**
    * 带条件分页查询数据
    */
    @PostMapping("/pagelist")
    public JsonResult page(@RequestBody CourseOrderQuery query){
        Page<CourseOrder> page = new Page<CourseOrder>(query.getPageNo(), query.getPageSize());
        page = courseOrderService.page(page);
        return JsonResult.success().setData(new PageList<CourseOrder>(page.getTotal(), page.getRecords()));
    }
}
